﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using HK.Reports;

namespace userHK_grid
{
    enum fh { s10n, s18n, Snds10n, Snds18n, s10o, s18o, Snds10o, Snds18o }
    enum g_style : int
    {
        col = 1,
        width = 2,
        captions = 3,
        font = 4,
        fontSize = 5,
        fontStyle = 6,
        typeCol = 7,
        SQLquery = 8,
        periodS = 9,
        periodPo = 10,
        name_col = 11,
        SQL_1 = 12,
        SQL_2 = 13,
        SQL_3 = 14,
        SQL_4 = 15,
        SQL_5 = 16,
        SQL_6 = 17,
        SQL_7 = 18,
        SQL_8 = 19,
        SQL_9 = 20,
        SQL_10 = 21,
        FIND_1 = 22,
        FIND_2 = 23,
        FIND_3 = 24,
        FIND_4 = 25,
        FIND_5 = 26,
        FIND_6 = 27,
        FIND_7 = 28,
        FIND_8 = 29,
        FIND_9 = 30,
        FIND_10 = 31,
        headReport = 32,
        serv = 33,
        shema_34 = 34,
        itog_35 = 35,
        land_36 = 36,
        keyFields_37 = 37,
        reportName_38 = 38,
        faed_39 = 39,
        rowCount_40 = 40,
        editIn_41 = 41,
        editOut_42 = 42,
        tableName_43 = 43,
        currentCellX_44 = 44,
        currentCellY_45 = 45
    }
    enum FAED { edit_col, look_cell, look_row, edit_cell, del_row, add_row }
    enum typeCell : int
    {
        editDisable = 0,
        editNumber = 1,
        editString = 2,
        editTehsir = 3
    }

    class grid_class
    {
        #region declaration
        functionService.prm_grid PLPg;
        functionService.connDB cnDB = new functionService.connDB();
        ETALON.FormKolZakaz inputNumber;
        city7.FormKEY inputText;
        ETALON.listAny lists;
        FontStyle fStyle;
        private Form ED;
        private Form qSQL;
        private Form Date;
        private TextBox qSQL_TB;
        private ListBox qSQL_LB;
        private Label LB;

        public DataGridView dataGridView10;
        public ToolStripComboBox toolStripComboBox10;
        public ToolStripComboBox toolStripComboBox20;
        public ToolStripStatusLabel toolStripStatusLabel20;
        public ToolStripTextBox toolStripTextBox10;
        string SQLforListAny = "SELECT 'DISABLE';";

        #endregion

        public grid_class(
            DataTable dt,
            DataGridView dataGridView1, 
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2, 
            ToolStripTextBox toolStripTextBox1)
            
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            PLPg = new functionService.prm_grid("PLP_grid");
            string ser = PLPg.tk((int)g_style.serv);
            toolStripComboBox20.Text = ser;
            cnDB.setConn(ser,"zarpl");
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost","zarpl");
                cnDB.co();
                PLPg.put((int)g_style.serv,"localHost");
            }
            DataTable dt1 = cnDB.selectAny(PLPg.tk((int)g_style.SQL_1));
            cnDB.cc();
            dataGridView10.DataSource = dt1;
            setTSMI("");
            getCount(); 
            setFormGrid(); 
            setComplete(); 
            setCurServ(); 
        }

        public grid_class(
            string SQL, 
            string shema, 
            string server,
            DataGridView dataGridView1,
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2,
            ToolStripTextBox toolStripTextBox1)
            
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            PLPg = new functionService.prm_grid("PLP_grid");
            PLPg.put((int)g_style.serv, server); 
            PLPg.put((int)g_style.shema_34, shema); 
            string ser = server;
            toolStripComboBox20=toolStripComboBox2;
            toolStripComboBox20.Text = ser;
            cnDB.setConn(ser, shema);
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost", "lists");
                cnDB.co();
                PLPg.put((int)g_style.serv, "localhost");
            }
            PLPg.put((int)g_style.SQL_1, SQL);
            DataTable dt1 = cnDB.selectAny(SQL);
            cnDB.cc();
            dataGridView10.DataSource = dt1;
            setTSMI("");
            getCount(); //dataGridView10, toolStripStatusLabel20);
            setFormGrid(); //dataGridView10, toolStripComboBox10);
            setComplete(); //toolStripTextBox10);
            setCurServ(); //toolStripComboBox20);
        }

        public grid_class(
            string SQL, 
            string shema, 
            string server, 
            string reportName,
            string tableName,
            DataGridView dataGridView1,
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2,
            ToolStripTextBox toolStripTextBox1)
            
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            PLPg = new functionService.prm_grid("PLP_grid_" + reportName);
            PLPg.put((int)g_style.serv, server);
            PLPg.put((int)g_style.shema_34, shema);
            PLPg.put((int)g_style.reportName_38, reportName);
            PLPg.put((int)g_style.tableName_43, tableName);
            string ser = server;
            toolStripComboBox20.Text = ser;
            cnDB.setConn(ser, shema);
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost", "lists");
                cnDB.co();
                PLPg.put((int)g_style.serv, "localhost");
            }
            PLPg.put((int)g_style.SQL_1, SQL);
            DataTable dt1 = cnDB.selectAny(SQL);
            cnDB.cc();
            dataGridView10.DataSource = dt1;
            setTSMI("");
            getCount(); 
            setFormGrid(); 
            setComplete();
            setCurServ();
            getKeyFields();
            setMode(FAED.look_cell);
        }

        public grid_class(
            string SQL, 
            string shema, 
            string server,
            string reportName,
            string tableName,
            string reportHead, 
            string reportItog,
            DataGridView dataGridView1,
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2,
            ToolStripTextBox toolStripTextBox1)
         
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            PLPg = new functionService.prm_grid("PLP_grid_" + reportName);
            PLPg.put((int)g_style.headReport, reportHead);
            PLPg.put((int)g_style.itog_35, reportItog);
            PLPg.put((int)g_style.serv, server);
            PLPg.put((int)g_style.shema_34, shema);
            PLPg.put((int)g_style.reportName_38, reportName);
            PLPg.put((int)g_style.tableName_43, tableName);
            string ser = server;
            toolStripComboBox20.Text = ser;
            cnDB.setConn(ser, shema);
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost", "lists");
                cnDB.co();
                PLPg.put((int)g_style.serv, "localhost");
            }
            PLPg.put((int)g_style.SQL_1, SQL);
            DataTable dt1 = cnDB.selectAny(SQL);
            cnDB.cc();
            dataGridView10.DataSource = dt1;
            setTSMI("");
            getCount();
            setFormGrid(); 
            setComplete();
            setCurServ(); 
            getKeyFields();
            setMode(FAED.look_cell);
        }

        public grid_class(
            string SQL, 
            string shema, 
            string server,
            string reportName,
            string tableName,
            string reportHead, 
            string reportItog, 
            bool land,
            DataGridView dataGridView1,
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2,
            ToolStripTextBox toolStripTextBox1)
    
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            PLPg = new functionService.prm_grid("PLP_grid_" + reportName);
            PLPg.put((int)g_style.headReport, reportHead);
            PLPg.put((int)g_style.itog_35, reportItog);
            PLPg.put((int)g_style.serv, server);
            PLPg.put((int)g_style.shema_34, shema);
            PLPg.put((int)g_style.land_36, land);
            PLPg.put((int)g_style.reportName_38, reportName);
            PLPg.put((int)g_style.tableName_43, tableName);
            string ser = server;
            toolStripComboBox20.Text = ser;
            cnDB.setConn(ser, shema);
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost", "lists");
                cnDB.co();
                PLPg.put((int)g_style.serv, "localhost");
            }
            PLPg.put((int)g_style.SQL_1, SQL);
            DataTable dt1 = cnDB.selectAny(SQL);
            cnDB.cc();
            dataGridView10.DataSource = dt1;
            setTSMI("");
            getCount(); 
            setFormGrid(); 
            setComplete(); 
            setCurServ(); 
            getKeyFields();
            setMode(FAED.look_cell); 
        }

        public grid_class(
            string SQL, 
            string shema, 
            string server,
            string reportName,
            string tableName,
            string reportHead, 
            string reportItog, 
            bool land, 
            string editColumns,
            DataGridView dataGridView1,
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2,
            ToolStripTextBox toolStripTextBox1)
 
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            PLPg = new functionService.prm_grid("PLP_grid_" + reportName);
            PLPg.put((int)g_style.headReport, reportHead);
            PLPg.put((int)g_style.itog_35, reportItog);
            PLPg.put((int)g_style.serv, server);
            PLPg.put((int)g_style.shema_34, shema);
            PLPg.put((int)g_style.land_36, land);
            PLPg.put((int)g_style.reportName_38, reportName);
            PLPg.put((int)g_style.tableName_43, tableName);
            PLPg.put((int)g_style.editIn_41, editColumns);
            string ser = server;
            toolStripComboBox20.Text = ser;
            cnDB.setConn(ser, shema);
            try
            {
                cnDB.co();
            }
            catch
            {
                cnDB.setConn("localhost", "lists");
                cnDB.co();
                PLPg.put((int)g_style.serv, "localhost");
            }
            PLPg.put((int)g_style.SQL_1, SQL);
            DataTable dt1 = cnDB.selectAny(SQL);
            cnDB.cc();
            dataGridView10.DataSource = dt1;
            setTSMI("");
            getCount();
            setFormGrid();
            setComplete();
            setCurServ();
            getKeyFields();
            setMode(FAED.look_cell);
        }

        public grid_class(
            DataView dv,
            DataGridView dataGridView1,
            ToolStripComboBox toolStripComboBox1,
            ToolStripComboBox toolStripComboBox2,
            ToolStripStatusLabel toolStripStatusLabel2,
            ToolStripTextBox toolStripTextBox1)
        {
            dataGridView10 = dataGridView1;
            toolStripComboBox10 = toolStripComboBox1;
            toolStripComboBox20 = toolStripComboBox2;
            toolStripStatusLabel20 = toolStripStatusLabel2;
            toolStripTextBox10 = toolStripTextBox1;

            dataGridView1.DataSource = dv;
        }

        #region workfun
        /// <summary>
        /// Загрузка параметров таблицы 
        /// - кол-во колонок
        /// - ширины столбцов
        /// - подписи столбцов
        /// - шрифт
        /// - размер шрифта
        /// - стиль шрифта
        /// </summary>
        public void setFormGrid() 
        {
            int i = dataGridView10.Columns.Count;
            int colCol = Convert.ToInt32(PLPg.tk((int)g_style.col));
            int i1 = 0;
            toolStripComboBox10.Items.Clear();
            if (colCol == i)
            {
                while (i1 < i)
                {
                    dataGridView10.Columns[i1].HeaderText = functionService.tagWork.readTAG(PLPg.tk((int)g_style.captions), i1);
                    dataGridView10.Columns[i1].Width = Convert.ToInt32(functionService.tagWork.readTAG(PLPg.tk((int)g_style.width), i1));
                    dataGridView10.Columns[i1].SortMode = DataGridViewColumnSortMode.NotSortable;
                    i1++;
                }
                updateListBox();
                setFontStyle();
                dataGridView10.Font = new Font(PLPg.tk((int)g_style.font), Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0)), fStyle);
            }
            else
            {
                while (i1 < i)
                {
                    dataGridView10.Columns[i1].SortMode = DataGridViewColumnSortMode.NotSortable;
                    toolStripComboBox10.Items.Add(dataGridView10.Columns[i1].HeaderText);
                    i1++;
                }
                setFontStyle();
                dataGridView10.Font = new Font(PLPg.tk((int)g_style.font), Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0)), fStyle);
            }
        }

        /// <summary>
        /// Сохранение параметров таблицы 
        /// - кол-во колонок
        /// - ширины столбцов
        /// - подписи столбцов
        /// - шрифт
        /// - размер шрифта
        /// - стиль шрифта
        /// </summary>
        public void saveDataXML() 
        {
            string w_array = "";
            string c_array = "";
            string c_type = "";
            int i1 = 1;
            int i = dataGridView10.Columns.Count;
            PLPg.put((int)g_style.col, i);
            while (i1 <= i)
            {
                if (i1 != i)
                {
                    w_array = w_array + string.Concat(dataGridView10.Columns[i1 - 1].Width, ";");
                    c_array = c_array + string.Concat(dataGridView10.Columns[i1 - 1].HeaderText, ";");
                    c_type = c_type + string.Concat(dataGridView10.Columns[i1 - 1].ValueType.ToString(), ";");
                }
                else if (i1 == i)
                {
                    w_array = w_array + string.Concat(dataGridView10.Columns[i1 - 1].Width);
                    c_array = c_array + string.Concat(dataGridView10.Columns[i1 - 1].HeaderText);
                    c_type = c_type + string.Concat(dataGridView10.Columns[i1 - 1].ValueType.ToString());
                }
                i1++;
            }
            PLPg.put((int)g_style.width, w_array);
            PLPg.put((int)g_style.captions, c_array);
            PLPg.put((int)g_style.font, dataGridView10.Font.Name.ToString());
            PLPg.put((int)g_style.fontSize, dataGridView10.Font.Size.ToString());
            PLPg.put((int)g_style.fontStyle, dataGridView10.Font.Style.ToString());
            PLPg.put((int)g_style.typeCol, c_type);
            //MessageBox.Show("Изменения сохранены.");


        }

        /// <summary>
        /// Экспорт содержимого таблицы в EXCEL (вместе с заголовками)
        /// filePath - полный путь с именем сохраняемого файла
        /// </summary>
        /// <param name="filePath"></param>
        public void saveDataXLS(string filePath) 
        {
            string file_path = filePath;
            int clmns = dataGridView10.Columns.Count;
            Int32 rows = dataGridView10.Rows.Count;
            Int32 i = 0;
            Int32 i1 = 0;
            string clType = "String";
            System.IO.StreamWriter file = new System.IO.StreamWriter(file_path);
            file.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            file.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            file.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
            file.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
            file.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
            file.WriteLine(" <Styles>");
            file.WriteLine("  <Style ss:ID=\"s21\">");
            file.WriteLine("   <NumberFormat ss:Format=\"Fixed\"/>");
            file.WriteLine("  </Style>");
            file.WriteLine(" </Styles>");
            file.WriteLine(" <Worksheet ss:Name=\"Table1\">");
            file.WriteLine("  <Table>");
            file.WriteLine("   <Row>");
            for (i = 0; i < clmns; i++)
            {
                file.WriteLine(string.Concat("    <Cell><Data ss:Type=\"String\">", functionService.tagWork.readTAG(PLPg.tk((int)g_style.captions), i), "</Data></Cell>"));
            }
            file.WriteLine("   </Row>");
            for (i1 = 0; i1 < rows; i1++)
            {
                file.WriteLine("   <Row>");
                for (i = 0; i < clmns; i++)
                {
                    file.WriteLine(string.Concat("    <Cell><Data ss:Type=\"", clType, "\">", dataGridView10.Rows[i1].Cells[i].Value, "</Data></Cell>"));
                }
                file.WriteLine("   </Row>");
            }
            file.WriteLine("  </Table>");
            file.WriteLine(" </Worksheet>");
            file.WriteLine("</Workbook>");
            file.Close();
        }

        /// <summary>
        /// Устанавливает значение в строке состояния
        /// texto - текст, который необходимо отобразить
        /// </summary>
        /// <param name="texto"></param>
        public void setTSMI(string mess)
        {
            //if (mess != "")
            //{
            //    int x = Control.MousePosition.X;
            //    int y = Control.MousePosition.Y;

            //    LB = new Label();
            //    LB.BorderStyle = BorderStyle.FixedSingle;
            //    LB.AutoSize = true;
            //    LB.Font = new Font("Arial", 8);
            //    LB.BackColor = Color.LightYellow;
            //    LB.ForeColor = Color.Black;
            //    LB.Text = mess;
            //    int wi = LB.Size.Width;
            //    Point p = new Point(x + 12, y + 25);
            //    LB.Location = LB.PointToClient(p);
            //    //this.Controls.Add(LB);
            //    LB.BringToFront();
            //}
            //else
            //{
            //    //this.Controls.Remove(LB);
            //}
        }

        /// <summary>
        /// Обработчик события клика мышкой на ячейке.
        /// В зависимости от режима FAED выбирается нужное действие.
        /// </summary>
        public void cellclick() 
        {
            PLPg.put((int)g_style.currentCellX_44, dataGridView10.CurrentCellAddress.X.ToString());
            PLPg.put((int)g_style.currentCellY_45, dataGridView10.CurrentCellAddress.Y.ToString());
            #region Если выбран режим редактирования наименований полей
            if (PLPg.tk((int)g_style.faed_39) == "edit_col")
            {
                //Инициализация формы
                int ind = dataGridView10.CurrentCellAddress.X;
                ED = new Form();

                // Создание ТекстБокса
                TextBox TB = new TextBox();
                TB.Text = functionService.tagWork.readTAG(PLPg.tk((int)g_style.captions), ind);
                TB.Location = new System.Drawing.Point(50, 0);
                TB.BorderStyle = BorderStyle.FixedSingle;
                TB.Width = 450;
                TB.Height = 25;
                TB.Font = new Font("Arial", 14);
                TB.Name = "TB";

                // Создание Лейбла
                Label LAB = new Label();
                LAB.TextAlign = ContentAlignment.MiddleCenter;
                LAB.Width = 51;
                LAB.Height = 29;
                LAB.Name = "LAB";
                LAB.Font = new Font("Arial", 14);
                LAB.BorderStyle = BorderStyle.FixedSingle;
                LAB.Text = ind.ToString();

                ED.Width = 500;
                ED.Height = 25;
                ED.Controls.Add(TB);
                ED.Controls.Add(LAB);
                ED.StartPosition = FormStartPosition.CenterParent;
                ED.FormBorderStyle = FormBorderStyle.None;
                TB.KeyDown += new KeyEventHandler(TB_KeyDown);
                ED.ShowDialog();
            }
            #endregion

            #region Если выбран режим редактирования значений в ячейке
            else if (PLPg.tk((int)g_style.faed_39) == "edit_cell")
            {
                int adressCell = dataGridView10.CurrentCellAddress.X;
                string type = functionService.tagWork.readTAG(PLPg.tk((int)g_style.editOut_42), adressCell);
                    #region Число (editNumber)
                    if (type == typeCell.editNumber.ToString())
                    {
                        inputNumber = new ETALON.FormKolZakaz("Введите количество (кг)", dataGridView10.CurrentCell.Value.ToString().Replace(",","."));
                        inputNumber.ShowDialog();
                        if (inputNumber.IsSelect)
                        {
                            if (PLPg.tk((int)g_style.tableName_43) == "tov_listtovsootvskladcity")
                            {
                                setKolGroup();
                            }
                            else if (PLPg.tk((int)g_style.tableName_43) == "oste_ceh_fakt")
                            {
                                setOstFakt();
                            }
                        }
                    }
                    #endregion
                    #region Строка (editString)
                    else if (type == typeCell.editString.ToString())
                    {
                        inputText = new city7.FormKEY(dataGridView10.CurrentCell.Value.ToString());
                        inputText.ShowDialog();
                        if (inputText.IsEnter)
                        {
                        }
                    }
                    #endregion
                    #region Технологическое сырье (editTehsir)
                    else if (type == typeCell.editTehsir.ToString())
                    {
                        SQLforListAny = "SELECT id AS cod, name FROM list_tehsir_ceh l ORDER BY name;";
                        cnDB.setConn(PLPg.tk((int)g_style.serv), PLPg.tk((int)g_style.shema_34));
                        cnDB.co();
                        DataTable listSir = cnDB.selectAny(SQLforListAny);
                        cnDB.cc();
                        lists = new ETALON.listAny(listSir);
                        lists.ShowDialog();
                        if (lists.IsOk)
                        {
                            setGroupSir();
                        }
                    }
                    #endregion
            }
            #endregion
        }

        /// <summary>
        /// Обработчик события редактирования значения ячейки
        /// </summary>
        public void celledit() 
        {
            if (PLPg.tk((int)g_style.faed_39) == "edit_cell")
            {
                #region Определяем сервер, схему и таблицу
                string server = PLPg.tk((int)g_style.serv);
                string db = PLPg.tk((int)g_style.shema_34);
                string table = PLPg.tk((int)g_style.tableName_43);
                #endregion

                #region Определяем массивы для значений индексов, типов индексов и наименований ключевых полей
                string[] indexValues = new string[10];
                string[] indexValuesUpdate = new string[10];
                string[] indexTypes = new string[10];
                string[] colIndex = functionService.tagWork.readTAGsArr(PLPg.tk((int)g_style.keyFields_37));
                #endregion

                #region Определяем значение, тип и адрес редактируемой ячейки
                int curCellAdress = dataGridView10.CurrentCellAddress.X;
                string curCellValue = dataGridView10.CurrentRow.Cells[curCellAdress].Value.ToString();
                string curCellType = dataGridView10.CurrentRow.Cells[curCellAdress].ValueType.ToString();
                string colUpdate = dataGridView10.CurrentCell.OwningColumn.Name.ToString();
                #endregion

                int countColIndex = colIndex.Length - 1;
                for (int i = 0; i < countColIndex; i++)
                {
                    indexValues[i] = dataGridView10.CurrentRow.Cells[colIndex[i]].Value.ToString();
                    indexTypes[i] = dataGridView10.CurrentRow.Cells[colIndex[i]].ValueType.ToString();
                }

                #region Первая часть запроса 'UPDATE shema.table SET '
                string updatePart1 = "";
                updatePart1 = "UPDATE " + db + "." + table + " SET ";
                #endregion

                #region Вторая часть запроса 'columnName = value '
                string updatePart2 = "";
                switch (curCellType)
                {
                    case "System.UInt16":
                    case "System.UInt32":
                    case "System.UInt64":
                    case "System.Int16":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Double":
                        updatePart2 = colUpdate + " = " + curCellValue + " ";
                        break;
                    case "System.String":
                        updatePart2 = colUpdate + " = '" + curCellValue + "' ";
                        break;
                    default:
                        updatePart2 = colUpdate + " = '" + curCellValue + "' ";
                        break;
                }
                #endregion

                #region Третья часть запроса 'WHERE key1 = value1 AND key2 = value2 ...'
                for (int i = 0; i < countColIndex; i++)
                {
                    switch (indexTypes[i])
                    {
                        case "System.UInt16":
                        case "System.UInt32":
                        case "System.UInt64":
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Double":
                            indexValuesUpdate[i] = indexValues[i];
                            break;
                        case "System.String":
                            indexValuesUpdate[i] = "'" + indexValues[i] + "'";
                            break;
                        default:
                            indexValuesUpdate[i] = "'" + indexValues[i] + "'";
                            break;
                    }
                }
                string updatePart3 = "WHERE " + colIndex[0] + " = " + indexValuesUpdate[0];
                if (countColIndex > 1)
                {
                    for (int i = 1; i < countColIndex; i++)
                    {
                        updatePart3 = updatePart3 + " AND " + colIndex[i] + " = " + indexValuesUpdate[i];
                    }
                }
                #endregion

                string updateQuery = "";
                updateQuery = updatePart1 + updatePart2 + updatePart3 + ";";
                try
                {
                    cnDB.setConn(server, db);
                    cnDB.co();
                    cnDB.UpdateData(updateQuery);
                    cnDB.cc();
                }
                catch
                {
                    MessageBox.Show("Ошибка! Проверьте правильность введенных данных.");
                }
            }
        }

        /// <summary>
        /// Обработчик события удаления записей
        /// </summary>
        public void deleterow() 
        {
            if (PLPg.tk((int)g_style.faed_39) == "del_row")
            {
                #region Определяем сервер, схему и таблицу
                string server = PLPg.tk((int)g_style.serv);
                string db = PLPg.tk((int)g_style.shema_34);
                string table = PLPg.tk((int)g_style.tableName_43);
                #endregion

                #region Определяем массивы для значений индексов, типов индексов и наименований ключевых полей
                string[] indexValues = new string[10];
                string[] indexValuesUpdate = new string[10];
                string[] indexTypes = new string[10];
                string[] colIndex = functionService.tagWork.readTAGsArr(PLPg.tk((int)g_style.keyFields_37));
                #endregion

                #region Определяем значение, тип и адрес редактируемой ячейки
                int curCellAdress = dataGridView10.CurrentCellAddress.X;
                string curCellValue = dataGridView10.CurrentRow.Cells[curCellAdress].Value.ToString();
                string curCellType = dataGridView10.CurrentRow.Cells[curCellAdress].ValueType.ToString();
                string colUpdate = dataGridView10.CurrentCell.OwningColumn.Name.ToString();
                #endregion

                int countColIndex = colIndex.Length - 1;
                for (int i = 0; i < countColIndex; i++)
                {
                    indexValues[i] = dataGridView10.CurrentRow.Cells[colIndex[i]].Value.ToString();
                    indexTypes[i] = dataGridView10.CurrentRow.Cells[colIndex[i]].ValueType.ToString();
                }

                #region Первая часть запроса 'DELETE FROM shema.table '
                string updatePart1 = "";
                updatePart1 = "DELETE FROM " + db + "." + table + " ";
                #endregion

                #region Вторая часть запроса 'columnName = value '
                string updatePart2 = "";
                switch (curCellType)
                {
                    case "System.UInt16":
                    case "System.UInt32":
                    case "System.UInt64":
                    case "System.Int16":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Double":
                        updatePart2 = colUpdate + " = " + curCellValue + " ";
                        break;
                    case "System.String":
                        updatePart2 = colUpdate + " = '" + curCellValue + "' ";
                        break;
                    default:
                        updatePart2 = colUpdate + " = '" + curCellValue + "' ";
                        break;
                }
                #endregion

                #region Третья часть запроса 'WHERE key1 = value1 AND key2 = value2 ...'
                for (int i = 0; i < countColIndex; i++)
                {
                    switch (indexTypes[i])
                    {
                        case "System.UInt16":
                        case "System.UInt32":
                        case "System.UInt64":
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Double":
                            indexValuesUpdate[i] = indexValues[i];
                            break;
                        case "System.String":
                            indexValuesUpdate[i] = "'" + indexValues[i] + "'";
                            break;
                        default:
                            indexValuesUpdate[i] = "'" + indexValues[i] + "'";
                            break;
                    }
                }
                string updatePart3 = "WHERE " + colIndex[0] + " = " + indexValuesUpdate[0];
                if (countColIndex > 1)
                {
                    for (int i = 1; i < countColIndex; i++)
                    {
                        updatePart3 = updatePart3 + " AND " + colIndex[i] + " = " + indexValuesUpdate[i];
                    }
                }
                #endregion

                string updateQuery = "";
                updateQuery = updatePart1 + updatePart3 + ";";
                try
                {
                    cnDB.setConn(server, db);
                    cnDB.co();
                    cnDB.UpdateData(updateQuery);
                    cnDB.cc();
                    refreshData();
                }
                catch
                {
                    MessageBox.Show("Ошибка!");
                }
                getCount();
            }
        }

        /// <summary>
        /// Обработчик события добавления записей
        /// </summary>
        public void addrow() 
        {
            if (PLPg.tk((int)g_style.faed_39) == "add_row" && Convert.ToInt32(PLPg.tk((int)g_style.rowCount_40)) < dataGridView10.RowCount)
            {
                #region Определяем сервер, схему и таблицу
                string server = PLPg.tk((int)g_style.serv);
                string db = PLPg.tk((int)g_style.shema_34);
                string table = PLPg.tk((int)g_style.tableName_43);
                #endregion

                #region Определяем массивы для значений индексов, типов индексов и наименований ключевых полей
                string[] indexValues = new string[10];
                string[] indexValuesUpdate = new string[10];
                string[] colValuesUpdate = new string[300];
                string[] indexTypes = new string[10];
                string[] colIndex = functionService.tagWork.readTAGsArr(PLPg.tk((int)g_style.keyFields_37));
                string[] colTypes = functionService.tagWork.readTAGsArr(PLPg.tk((int)g_style.typeCol));
                string colNames = dataGridView10.CurrentRow.Cells[0].OwningColumn.Name.ToString() + ",";
                #endregion

                #region Определяем значение, тип и адрес редактируемой ячейки
                int curCellAdress = dataGridView10.CurrentCellAddress.X;
                string curCellValue = dataGridView10.CurrentRow.Cells[curCellAdress].Value.ToString();
                string curCellType = dataGridView10.CurrentRow.Cells[curCellAdress].ValueType.ToString();
                string colUpdate = dataGridView10.CurrentCell.OwningColumn.Name.ToString();
                #endregion

                int countColIndex = colIndex.Length - 1;
                int countColTable = dataGridView10.Columns.Count;

                for (int i = 1; i < countColTable; i++)
                {
                    if (i == countColTable - 1)
                    {
                        colNames = colNames + dataGridView10.CurrentRow.Cells[i].OwningColumn.Name.ToString();
                    }
                    else
                    {
                        colNames = colNames + dataGridView10.CurrentRow.Cells[i].OwningColumn.Name.ToString() + ",";
                    }
                }

                for (int i = 0; i < countColIndex; i++)
                {
                    indexValues[i] = dataGridView10.CurrentRow.Cells[colIndex[i]].Value.ToString();
                    indexTypes[i] = dataGridView10.CurrentRow.Cells[colIndex[i]].ValueType.ToString();
                }

                #region Первая часть запроса 'INSERT INTO shema.tblname(col1,col2,col3,....) VALUES '
                string updatePart1 = "";
                updatePart1 = "INSERT INTO " + db + "." + table + " (" + colNames + ") VALUES ";
                #endregion

                #region Третья часть запроса '(val, val2, val3,....);'
                for (int i = 0; i < countColTable; i++)
                {
                    switch (colTypes[i])
                    {
                        case "System.UInt16":
                        case "System.UInt32":
                        case "System.UInt64":
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Double":
                            colValuesUpdate[i] = dataGridView10.CurrentRow.Cells[i].Value.ToString();
                            break;
                        case "System.String":
                            colValuesUpdate[i] = "'" + dataGridView10.CurrentRow.Cells[i].Value.ToString() + "'";
                            break;
                        default:
                            colValuesUpdate[i] = "'" + dataGridView10.CurrentRow.Cells[i].Value.ToString() + "'";
                            break;
                    }
                }
                string updatePart3 = "(" + colValuesUpdate[0];
                if (countColTable > 1)
                {
                    for (int i = 1; i < countColTable; i++)
                    {
                        if (i == countColTable - 1)
                        {
                            updatePart3 = updatePart3 + "," + colValuesUpdate[i] + ");";
                        }
                        else
                        {
                            updatePart3 = updatePart3 + "," + colValuesUpdate[i];
                        }
                    }

                }
                #endregion

                string updateQuery = updatePart1 + updatePart3;
                try
                {
                    cnDB.setConn(server, db);
                    cnDB.co();
                    cnDB.UpdateData(updateQuery);
                    cnDB.cc();
                }
                catch
                {
                    MessageBox.Show("Ошибка!");
                }
                getCount();
            }
        }

        /// <summary>
        /// Установка режима таблицы (выделение по строкам, столбцам, 
        /// редактирование заголовков)
        /// </summary>
        /// <param name="m"></param>
        public void setMode(FAED m) 
        {
            #region Определяем общее кол-во колонок
            int col = dataGridView10.Columns.Count;
            #endregion

            #region Просмотр значений look_cell
            if (m == FAED.look_cell)
            {
                dataGridView10.SelectionMode = DataGridViewSelectionMode.CellSelect;
                dataGridView10.EditMode = DataGridViewEditMode.EditProgrammatically;
                dataGridView10.DefaultCellStyle.BackColor = Color.White;
                for (int i = 0; i < col; i++)
                {
                    dataGridView10.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                PLPg.put((int)g_style.faed_39, FAED.look_cell.ToString());
            }
            #endregion

            #region Редактирование заголовков edit_col
            else if (m == FAED.edit_col)
            {
                for (int i = 0; i < col; i++)
                {
                    dataGridView10.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                dataGridView10.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
                dataGridView10.EditMode = DataGridViewEditMode.EditProgrammatically;
                dataGridView10.DefaultCellStyle.BackColor = Color.LightGreen;
                PLPg.put((int)g_style.faed_39, FAED.edit_col.ToString());
            }
            #endregion

            #region Выделение по строкам look_row
            else if (m == FAED.look_row)
            {
                dataGridView10.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dataGridView10.EditMode = DataGridViewEditMode.EditProgrammatically;
                dataGridView10.Columns[0].DefaultCellStyle.BackColor = Color.Wheat;
                for (int i = 0; i < col; i++)
                {
                    dataGridView10.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                PLPg.put((int)g_style.faed_39, FAED.look_row.ToString());
            }
            #endregion

            #region Редактирование записей edit_cell
            else if (m == FAED.edit_cell)
            {
                dataGridView10.SelectionMode = DataGridViewSelectionMode.CellSelect;
                dataGridView10.DefaultCellStyle.BackColor = Color.LightGreen;

                int[] plpEdCol = functionService.tagWork.readTAGiArr(PLPg.tk((int)g_style.editIn_41));
                string editStringOut = "";
                int plpedColCount = plpEdCol.Length;

                for (int i = 0; i < col; i++)
                {
                    editStringOut = editStringOut + get0123(plpEdCol[i]) + ";";
                    dataGridView10.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                PLPg.put((int)g_style.faed_39, FAED.edit_cell.ToString());
                PLPg.put((int)g_style.editOut_42, editStringOut);
            }
            #endregion

            #region Удаление записей del_row
            else if (m == FAED.del_row)
            {
                dataGridView10.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dataGridView10.EditMode = DataGridViewEditMode.EditProgrammatically;
                dataGridView10.DefaultCellStyle.BackColor = Color.Tomato;
                for (int i = 0; i < col; i++)
                {
                    dataGridView10.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                PLPg.put((int)g_style.faed_39, FAED.del_row.ToString());
            }
            #endregion

            #region Добавление записей add_row
            else if (m == FAED.add_row)
            {
                dataGridView10.SelectionMode = DataGridViewSelectionMode.CellSelect;
                dataGridView10.EditMode = DataGridViewEditMode.EditOnEnter;
                dataGridView10.DefaultCellStyle.BackColor = Color.LightBlue;
                for (int i = 0; i < col; i++)
                {
                    dataGridView10.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                PLPg.put((int)g_style.faed_39, FAED.add_row.ToString());
            }
            #endregion

        }

        /// <summary>
        /// Функция возвращает editString, editNumber
        /// 0 - редактирование недоступно (editDisable)
        /// 1 - числа (editNumber)
        /// 2 - строка (editString)
        /// 3 - технологическое сырье (editTehsir)
        /// </summary>
        /// <param name="val">0,1,2,3,4,5...</param>
        /// <returns></returns>
        public string get0123(int val)
        {
            switch (val)
            {
                case 0:
                    return typeCell.editDisable.ToString();
                case 1:
                    return typeCell.editNumber.ToString();
                case 2:
                    return typeCell.editString.ToString();
                case 3:
                    return typeCell.editTehsir.ToString();
                default:
                    return typeCell.editDisable.ToString();
            }
        }

        /// <summary>
        /// Загрузка стиля шрифта
        /// </summary>
        public void setFontStyle()
        {
            fStyle = FontStyle.Regular;
            switch (PLPg.tk((int)g_style.fontStyle))
            {
                case "Regular": fStyle = FontStyle.Regular; break;
                case "Bold": fStyle = FontStyle.Bold; break;
                case "Italic": fStyle = FontStyle.Italic; break;
                case "Bold, Italic": fStyle = FontStyle.Bold | FontStyle.Italic; break;
                case "Underline": fStyle = FontStyle.Underline; break;
                case "Strikeout": fStyle = FontStyle.Strikeout; break;
            }
        }

        /// <summary>
        /// Получаем количество загруженных строк
        /// </summary>
        public void getCount() 
        {
            PLPg.put((int)g_style.rowCount_40, dataGridView10.RowCount.ToString());
            toolStripStatusLabel20.Text = string.Concat("RowCount = ", (dataGridView10.RowCount).ToString());
        }

        /// <summary>
        /// Форма SQL запроса
        /// </summary>
        public void querySQL()
        {
            //Инициализация формы
            qSQL = new Form();
            qSQL.Width = 610;
            qSQL.Height = 400;
            qSQL.StartPosition = FormStartPosition.CenterParent;
            qSQL.FormBorderStyle = FormBorderStyle.FixedToolWindow;

            // Создание ЛистБокса
            qSQL_LB = new ListBox();
            qSQL_LB.Font = new Font("Arial", 12);
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_1));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_2));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_3));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_4));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_5));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_6));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_7));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_8));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_9));
            qSQL_LB.Items.Add(PLPg.tk((int)g_style.SQL_10));
            qSQL_LB.Width = 600;
            qSQL_LB.Height = 200;
            qSQL_LB.Click += new EventHandler(qSQL_LB_Click);
            qSQL_LB.DoubleClick += new EventHandler(qSQL_LB_DoubleClick);

            // Создание ТекстБокса
            qSQL_TB = new TextBox();
            qSQL_TB.Text = "";
            qSQL_TB.BorderStyle = BorderStyle.FixedSingle;
            qSQL_TB.Location = new Point(0, 190);
            qSQL_TB.Width = 600;
            qSQL_TB.Height = 200;
            qSQL_TB.Multiline = true;
            qSQL_TB.Font = new Font("Arial", 14);
            qSQL_TB.KeyDown += new KeyEventHandler(qSQL_TB_KeyDown);

            qSQL.Text = "ВВЕДИТЕ SQL ЗАПРОС";
            qSQL.Controls.Add(qSQL_TB);
            qSQL.Controls.Add(qSQL_LB);
            qSQL.ShowDialog();
        }

        /// <summary>
        /// Форма выбора периода
        /// </summary>
        public void datePik()
        {
            // Инициализация формы
            Date = new Form();
            Date.Text = "Период";
            Date.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            Date.StartPosition = FormStartPosition.CenterParent;
            Date.Width = 355;
            Date.Height = 250;

            // Создание MonthCalendar 1
            MonthCalendar dtPik1 = new MonthCalendar();
            dtPik1.Font = new Font("Arial", 10);
            dtPik1.SelectionStart = Convert.ToDateTime(PLPg.tk((int)g_style.periodS));
            dtPik1.DateSelected += new DateRangeEventHandler(dtPik1_DateSelected);

            // Создание MonthCalendar 2
            MonthCalendar dtPik2 = new MonthCalendar();
            dtPik2.Font = new Font("Arial", 10);
            dtPik2.Location = new System.Drawing.Point(175, 0);
            dtPik2.SelectionStart = Convert.ToDateTime(PLPg.tk((int)g_style.periodPo));
            dtPik2.DateSelected += new DateRangeEventHandler(dtPik2_DateSelected);

            // Создание кнопки ОК
            Button bOk = new Button();
            bOk.Text = "OK";
            bOk.Location = new Point(140, 190);
            bOk.Click += new EventHandler(bOk_Click);

            // Добавление элементов
            Date.Controls.Add(dtPik1);
            Date.Controls.Add(dtPik2);
            Date.Controls.Add(bOk);
            Date.ShowDialog();
        }

        /// <summary>
        /// Обновление ЛистБокса с полями
        /// </summary>
        public void updateListBox() 
        {
            toolStripComboBox10.Items.Clear();
            int i = dataGridView10.Columns.Count;
            int i1 = 0;
            while (i1 < i)
            {
                toolStripComboBox10.Items.Add(dataGridView10.Columns[i1].HeaderText);
                i1++;
            }
            toolStripComboBox10.SelectedIndex = 0;
        }

        /// <summary>
        /// Заполнение списка автозавершения ТекстБокса
        /// </summary>
        public void setComplete() 
        {
            toolStripTextBox10.AutoCompleteCustomSource.Clear();
            for (int i = 22; i <= 31; i++)
            {
                toolStripTextBox10.AutoCompleteCustomSource.Add(PLPg.tk(i));
            }
        }

        /// <summary>
        /// Вывод на печать через класс HK.Reports
        /// </summary>
        public void printTable() 
        {
            DataTable printTab = (DataTable)dataGridView10.DataSource;
            Report r = new Report(
                "Report",
                printTab,
                PLPg.tk((int)g_style.headReport),
                PLPg.tk((int)g_style.itog_35),
                PLPg.tk((int)g_style.width),
                PLPg.tk((int)g_style.captions),
                Convert.ToBoolean(PLPg.tk((int)g_style.land_36)));
            r.ShowReport();
        }

        /// <summary>
        /// Отображение текущего сервера
        /// </summary>
        public void setCurServ() 
        {
            toolStripComboBox20.Text = PLPg.tk((int)g_style.serv);
        }

        /// <summary>
        /// Определение ключевых полей
        /// </summary>
        public void getKeyFields()
        {
            string server = PLPg.tk((int)g_style.serv);
            string shema = PLPg.tk((int)g_style.shema_34);
            string table = PLPg.tk((int)g_style.tableName_43);
            cnDB.setConn(server, shema);
            cnDB.co();
            string fields = Convert.ToString(cnDB.selectScalar("CALL getKeys('" + shema + "','" + table + "');"));
            cnDB.cc();
            PLPg.put((int)g_style.keyFields_37, "");
            PLPg.put((int)g_style.keyFields_37, fields);
        }

        /// <summary>
        /// Обновление данных таблицы
        /// </summary>
        public void refreshData() 
        {
            string server = PLPg.tk((int)g_style.serv);
            string db = PLPg.tk((int)g_style.shema_34);
            cnDB.setConn(server, db);
            cnDB.co();
            DataTable dt = cnDB.selectAny(PLPg.tk((int)g_style.SQL_1));
            cnDB.cc();
            dataGridView10.DataSource = dt;
        }
        #endregion

        #region Функции from evets
        public void toolStripMenuItem2_Click_fun(object sender, EventArgs e) 
        {
            SaveFileDialog SV = new SaveFileDialog();
            SV.Filter = "MSExcel files (*.xls)|*.xls|All files (*.*)|*.*";
            SV.FilterIndex = 1;
            SV.RestoreDirectory = true;
            if (SV.ShowDialog() == DialogResult.OK)
            {
                saveDataXLS(SV.FileName.ToString());
                MessageBox.Show(string.Concat("Экспорт в файл ", SV.FileName.ToString(), " успешно завершен."));
            }
        } 
        public void toolStripMenuItem3_Click_fun() 
        {
            FontDialog fd = new FontDialog();
            fd.Font = new Font(PLPg.tk((int)g_style.font), Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0)), fStyle);
            if (fd.ShowDialog() == DialogResult.OK)
            {
                dataGridView10.Font = new Font(fd.Font.Name, fd.Font.Size, fd.Font.Style);
                PLPg.put((int)g_style.font, fd.Font.Name);
                PLPg.put((int)g_style.fontSize, fd.Font.Size);
                PLPg.put((int)g_style.fontStyle, fd.Font.Style);
            }
        } 
        public void toolStripMenuItem4_Click_fun(object sender, EventArgs e) 
        {
            int FSize = Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0));
            FSize = FSize + 2;
            PLPg.put((int)g_style.fontSize, FSize);
            setFontStyle();
            dataGridView10.Font = new Font(PLPg.tk((int)g_style.font), FSize, fStyle);
            dataGridView10.AutoResizeColumns();
        }
        public void toolStripMenuItem5_Click_fun(object sender, EventArgs e) 
        {
            int FSize = Convert.ToInt32(Math.Round(Convert.ToDouble(PLPg.tk((int)g_style.fontSize)), 0));
            FSize = FSize - 2;
            PLPg.put((int)g_style.fontSize, FSize);
            setFontStyle();
            dataGridView10.Font = new Font(PLPg.tk((int)g_style.font), FSize, fStyle);
            dataGridView10.AutoResizeColumns();
        }

        public void qSQL_LB_Click(object sender, EventArgs e)
        {
            qSQL_TB.Text = qSQL_LB.SelectedItem.ToString();
        }
        public void TB_KeyDown(object sender, KeyEventArgs e)
        {
            /*, 
            DataGridView dataGridView1, ToolStripComboBox ToolStripComboBox1*/
            if (e.KeyCode == Keys.Enter)
            {
                string w_array = "";
                string[] colu = PLPg.tk((int)g_style.captions).Split(';');
                int contArray = colu.Count();
                int i = 0;
                colu[dataGridView10.CurrentCellAddress.X] = (sender as TextBox).Text;
                for (i = 0; i < contArray; i++)
                {
                    w_array = w_array + string.Concat(colu[i], ";");
                }
                PLPg.put((int)g_style.captions, w_array);
                setFormGrid();
                ED.Close();
            }
            else if (e.KeyCode == Keys.Escape)
            {
                ED.Close();
            }
        }
        public void qSQL_TB_KeyDown(object sender, KeyEventArgs e)
        {
            /*
            DataGridView dataGridView1, ToolStripComboBox ToolStripComboBox1,
            ToolStripStatusLabel ToolStripStatusLabel2
             */

            string[] sqlQuery = new string[30];
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    for (int i = 12; i <= 21; i++)
                    {
                        sqlQuery[i] = PLPg.tk(i);
                    }
                    cnDB.setConn(PLPg.tk((int)g_style.serv), PLPg.tk((int)g_style.shema_34));
                    cnDB.co();
                    string TB_text = (sender as TextBox).Text;
                    DataTable dtq = cnDB.selectAny(TB_text);
                    cnDB.cc();
                    dataGridView10.DataSource = dtq;
                    if (TB_text != PLPg.tk((int)g_style.SQL_1))
                    {
                        for (int i = 12; i <= 20; i++)
                        {
                            PLPg.put(i + 1, sqlQuery[i]);
                        }
                        PLPg.put((int)g_style.SQL_1, TB_text);
                    }
                    updateListBox();
                    saveDataXML();
                    qSQL.Close();
                }
                catch (Exception emes) { MessageBox.Show(emes.Message); }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                qSQL.Close();
            }
            getCount();
        }
        public void qSQL_LB_DoubleClick(object sender, EventArgs e)
        {

            /*, 
                        DataGridView dataGridView1, ToolStripComboBox ToolStripComboBox1, 
                        ToolStripStatusLabel ToolStripStatusLabel2*/
            string[] sqlQuery = new string[30];
            try
            {
                for (int i = 12; i <= 21; i++)
                {
                    sqlQuery[i] = PLPg.tk(i);
                }
                cnDB.setConn("serverExp", "zarpl");
                cnDB.co();
                string LB_text = (sender as ListBox).Text;
                DataTable dtq = cnDB.selectAny(LB_text);
                cnDB.cc();
                dataGridView10.DataSource = dtq;
                if (LB_text != PLPg.tk((int)g_style.SQL_1))
                {
                    for (int i = 12; i <= 20; i++)
                    {
                        PLPg.put(i + 1, sqlQuery[i]);
                    }
                    PLPg.put((int)g_style.SQL_1, LB_text);
                }
                updateListBox();
                saveDataXML();
                qSQL.Close();
            }
            catch (Exception emes) { MessageBox.Show(emes.Message); }
            getCount();
        }
        public void dtPik1_DateSelected(object sender, DateRangeEventArgs e)
        {
            PLPg.put((int)g_style.periodS, (sender as MonthCalendar).SelectionStart.ToShortDateString());
        }
        public void dtPik2_DateSelected(object sender, DateRangeEventArgs e)
        {
            PLPg.put((int)g_style.periodPo, (sender as MonthCalendar).SelectionStart.ToShortDateString());
        }
        public void bOk_Click(object sender, EventArgs e)
        {
            //DataGridView dataGridView1


            string s = PLPg.tk((int)g_style.periodS).Replace('.', '/');
            string po = PLPg.tk((int)g_style.periodPo).Replace('.', '/');
            string nameCol = PLPg.tk((int)g_style.name_col);
            ((DataTable)dataGridView10.DataSource).DefaultView.RowFilter = string.Concat(nameCol, " >= '", s, "' AND ", nameCol, " <= '", po, "'");
            Date.Close();
        }

        public void toolStripComboBox1_SelectedIndexChanged_fun()
        {
            string nameCol = ((DataTable)dataGridView10.DataSource).Columns[toolStripComboBox10.SelectedIndex].ColumnName;
            PLPg.put((int)g_style.name_col, nameCol);
            if (functionService.tagWork.readTAG(PLPg.tk((int)g_style.typeCol), toolStripComboBox10.SelectedIndex) == "System.DateTime")
            {
                toolStripTextBox10.Enabled = false;
                datePik();
            }
            else
            {
                toolStripTextBox10.Enabled = true;
            }
            getCount();
        }
        public void toolStripTextBox1_KeyUp_fun(KeyEventArgs e) 
        {
            string strFind = toolStripTextBox10.Text;
            string[] find = new string[10];
            int i1 = 0;
            if (strFind != "")
            {
                if (e.KeyCode == Keys.Enter)
                {
                    for (int i = 22; i <= 31; i++)
                    {
                        find[i1] = PLPg.tk(i);
                        i1++;
                    }
                    i1 = 0;
                    for (int i = 22; i <= 30; i++)
                    {
                        PLPg.put(i + 1, find[i1]);
                        i1++;
                    }
                    PLPg.put((int)g_style.FIND_1, strFind);
                    string nameCol = ((DataTable)dataGridView10.DataSource).Columns[toolStripComboBox10.SelectedIndex].ColumnName;
                    DataTable datT = (DataTable)dataGridView10.DataSource;
                    switch (functionService.tagWork.readTAG(PLPg.tk((int)g_style.typeCol), toolStripComboBox10.SelectedIndex).ToString())
                    {
                        case "System.UInt16":
                        case "System.UInt32":
                        case "System.UInt64":
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Double":
                            ((DataTable)dataGridView10.DataSource).DefaultView.RowFilter = string.Concat(nameCol, " = ", strFind);
                            break;
                        case "System.String":
                            ((DataTable)dataGridView10.DataSource).DefaultView.RowFilter = string.Concat(nameCol, " LIKE '%", strFind, "%'");
                            break;
                    }
                    setComplete();
                }
            }
            else
            {
                ((DataTable)dataGridView10.DataSource).DefaultView.RowFilter = null;
            }
            getCount();
        }
        public void toolStripMenuItem20_Click_fun() 
        {
            string fields = PLPg.tk((int)g_style.keyFields_37);
            if (fields == "")
            {
                MessageBox.Show("Добавление невозможно т.к. входной параметр не является таблицей.");
                setMode(FAED.look_cell); 
            }
            else
            {
                setMode(FAED.add_row);
            }
        }
        public void toolStripMenuItem19_Click_fun() 
        {
            string fields = PLPg.tk((int)g_style.keyFields_37);
            if (fields == "")
            {
                MessageBox.Show("Удаление невозможно т.к. входной параметр не является таблицей.");
                setMode(FAED.look_cell);
            }
            else
            {
                setMode(FAED.del_row);
            }
        }
        public void toolStripMenuItem18_Click_fun() 
        {
            string fields = PLPg.tk((int)g_style.keyFields_37);
            if (fields == "")
            {
                MessageBox.Show("Редактирование невозможно т.к. входной параметр не является таблицей.");
                setMode(FAED.look_cell);
            }
            else
            {
                setMode(FAED.edit_cell);
            }
        }
        
        public void toolStripComboBox2_SelectedIndexChanged_fun()
        {
            PLPg.put((int)g_style.SQL_1, string.Concat("CALL ceh_getRecept(", functionService.nameCod.readCod(toolStripComboBox20.Text), ");"));
            refreshData();
           // PLPg.put((int)g_style.serv, toolStripComboBox20.Text);
        }
        #endregion

        # region Функции привязанные к проекту City7

        /// <summary>
        /// Ввод фактических остатков
        /// </summary>
        private void setOstFakt() 
        {
            int periodpo;
            int periods;
            int X = dataGridView10.CurrentCellAddress.X;
            int Y = dataGridView10.CurrentCellAddress.Y;
            string server = PLPg.tk((int)g_style.serv);
            string shema = PLPg.tk((int)g_style.shema_34);
            string table = PLPg.tk((int)g_style.tableName_43);
            //MessageBox.Show(table);
            functionService.prm_city prm = new functionService.prm_city();
            if (PLPg.tk((int)g_style.reportName_38) == "GetOstCeh_day")
            {
                periodpo = functionService.DATECOD.date_to_cod_int(prm.tk(ETALON.param.day_work_7));
                periods = functionService.DATECOD.date_to_cod_int(prm.tk(ETALON.param.day_work_7));
            }
            else
            {
                periodpo = functionService.DATECOD.date_to_cod_int(prm.tk(ETALON.param.period_p_6));
                periods = functionService.DATECOD.date_to_cod_int(prm.tk(ETALON.param.period_s_5));
            }
            string SQLdel = "DELETE FROM " + shema + "." + table + " WHERE ct = " + functionService.nameCod.readCod(dataGridView10.CurrentRow.Cells[1].Value.ToString()) + " AND dt = " + periodpo + ";";
            string SQLins = string.Concat("INSERT INTO ", shema, ".", table, "(ct, name, kol, dt) VALUES (",
                functionService.nameCod.readCod(dataGridView10.CurrentRow.Cells[1].Value.ToString()), ",'",
                functionService.nameCod.readName(dataGridView10.CurrentRow.Cells[1].Value.ToString()), "',",
                inputNumber.valueEnter, ",", periodpo, ");");
            cnDB.setConn(server, shema);
            cnDB.co();
            cnDB.UpdateData(SQLdel);
            cnDB.UpdateData(SQLins);
            cnDB.cc();
            refreshData();
        }

        /// <summary>
        /// Группировка тех сырья
        /// </summary>
        private void setGroupSir()
        {
            int X = dataGridView10.CurrentCellAddress.X;
            int Y = dataGridView10.CurrentCellAddress.Y;
            string server = PLPg.tk((int)g_style.serv);
            string shema = PLPg.tk((int)g_style.shema_34);
            string table = PLPg.tk((int)g_style.tableName_43);
            string SQLupdate = string.Concat("UPDATE city.", table, " SET ctCity = ",
                lists.sCod, " WHERE ctSklad = ",
                functionService.nameCod.readCod(dataGridView10.CurrentRow.Cells[0].Value.ToString()), ";");
            cnDB.setConn(server, shema);
            cnDB.co();
            cnDB.UpdateData(SQLupdate);
            cnDB.cc();
            refreshData();
            //MessageBox.Show(SQLupdate);
        }

        /// <summary>
        /// Учет количества грамм на единицу сырья, поступающего со склада
        /// </summary>
        private void setKolGroup()
        {
            int X = dataGridView10.CurrentCellAddress.X;
            int Y = dataGridView10.CurrentCellAddress.Y;
            string server = PLPg.tk((int)g_style.serv);
            string shema = PLPg.tk((int)g_style.shema_34);
            string table = PLPg.tk((int)g_style.tableName_43);
            string SQLUpdate = string.Concat("UPDATE ",shema,".",table," SET naEd = ",
                inputNumber.valueEnter," WHERE ctSklad = ",
                functionService.nameCod.readCod(dataGridView10.CurrentRow.Cells[0].Value.ToString()),";");
            cnDB.setConn(server, shema);
            cnDB.co();
            cnDB.UpdateData(SQLUpdate);
            cnDB.cc();
            refreshData();
        }

        /// <summary>
        /// Заполнение списка продукции для редактирования рецептур
        /// </summary>
        //private void setListSC()
        //{
        //    toolStripComboBox20.Enabled = true;
        //    toolStripComboBox20.Items.Clear();
        //    string server = PLPg.tk((int)g_style.serv);
        //    string shema = PLPg.tk((int)g_style.shema_34);
        //    cnDB.setConn(server, shema);
        //    cnDB.co();
        //    DataTable prod = cnDB.selectAny(string.Concat("SELECT ",
        //        "CAST(concat(CAST(name AS CHAR),' (',cod,')') AS CHAR) AS prod ",
        //        "FROM list_sc l ORDER BY name;"));
        //    cnDB.cc();
        //    int count = prod.Rows.Count;
        //    //toolStripComboBox20.ComboBox.DataSource = prod;
        //    //MessageBox.Show(count.ToString());
        //    for (int i = 0; i < count; i++)
        //    {
        //        toolStripComboBox20.Items.Add(prod.Rows[i]["prod"].ToString());
        //    }
        //    toolStripComboBox20.SelectedIndex = 0;
        //}

        #endregion
    }
}
